package org.truenewx.tnxjee.repo.jpa.converter;

import java.time.Instant;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

import org.apache.commons.lang3.StringUtils;
import org.truenewx.tnxjee.core.util.TemporalUtil;

/**
 * Instant-字符串的属性转换器
 */
@Converter
public abstract class InstantStringAttributeConverter implements AttributeConverter<Instant, String> {

    private final String pattern;

    public InstantStringAttributeConverter(String pattern) {
        this.pattern = pattern;
    }

    @Override
    public String convertToDatabaseColumn(Instant attribute) {
        if (attribute == null) {
            return null;
        }
        return TemporalUtil.format(attribute, this.pattern);
    }

    @Override
    public Instant convertToEntityAttribute(String dbData) {
        if (StringUtils.isBlank(dbData)) {
            return null;
        }
        return TemporalUtil.parse(Instant.class, dbData, this.pattern);
    }

}
